// 产品列表table
var $productTable = $('#productList');
// 已选产品table
var $selectedTable = $('#selectedList');

$(function () {
    // getProductList();
    // getChoosedProductList();

    productList();
    selectProductList();

    /*$('#selectedList').bootstrapTable({
        classes: 'table table-bordered table-hover table-striped',
        search: true,
        visibleSearch: true,
        pagination: true,
        pageSize: 5,
        uniqueId: 'productId',
        idField: 'productId',
        columns: [
            {field: 'productId', title: 'id', visible: false},
            {field: 'productName', title: '产品名称'},
            {field: 'operate', title: '操作', width: '80', align: 'right'},
            {field: 'productCategories', title: '操作',visible: false}
        ],
        formatNoMatches:function(){
            return "暂无产品";
        },
    });*/

});

/**
 * 获取产品列表初始化表格
 * */
function productList() {
    let activityId = $("#activityId").val();
    $productTable.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: "/customerProductActivityRelation/selectProductDropDownNotSelectedListByActivityId?activityId="+ activityId,
        method: 'get',
        search: true,
        visibleSearch: true,
        customSearch: customSearch,
        pagination: true,
        pageSize: 5,
        uniqueId: 'productId',
        idField: 'productId',
        columns: [
            {field: 'productName', title: '产品名称'},
            {field: 'operate', title: '操作', align: 'right', width: '100', formatter: operateFormatter},
            {field: 'productCategories', title: '产品分类',visible: false},
            {field: 'productFinalPrice', title: '价格',visible: false}
        ],
        formatNoMatches:function(){
            return "暂无产品";
        },
        responseHandler: function (result) {
            if (result.code == "000000") {
                console.log(result)
                var obj = {
                    "rows": result.data
                };
            } else {
                var obj = {
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function (data) {
        }
    })
}

/**
 * 自定义搜索
 * data:    表格数据
 * text:    搜索的文字
 * filter:  filterBy方法中的过滤器对象
 * */
function customSearch(data, text) {
    return data.filter(function (row) {
        return (row.productName+"").indexOf(text) > -1
    });
}

// 自定义添加操作
function operateFormatter(value, row, index) {
    var result = '<button type="button" class="btn btn-default" onclick="btnOperate(\'' + row.productId + '\', \'' + row.productName + '\', \'' + row.productCategories + '\', true)"><i class="mdi mdi-plus"></i>添加</button>';
    return result;
}

/**
 * 点击添加事件
 * productId:       产品id
 * productName:     产品名称
 * flag:            添加删除控制开关
 * */
function btnOperate(productId, productName, productCategories, flag) {
    var tableA = $productTable;
    var tableB = $selectedTable;
    if (!flag) {
        tableA = $selectedTable;
        tableB = $productTable;
    }
    // 删除操作
    tableA.bootstrapTable('removeByUniqueId', productId);
    // 添加操作
    tableB.bootstrapTable('insertRow', {
        index: 0,
        row: {
            productId: productId,
            productName: productName,
            productCategories:productCategories,
            productFinalPrice:''
            // operate: '<button type="button" class="btn btn-default" onclick="btnOperate(\'' + productId + '\', \'' + productName + '\', false)"><i class="mdi mdi-delete"></i>移除</button>'
        }
    });
}

//取消新增活动
function cancelProductActivity(){
    window.location.reload();
}

/**
 * 获取已选产品列表
 * */
function selectProductList() {
    let activityId = $("#activityId").val();
    $selectedTable.bootstrapTable({
        classes: 'table table-hover table-bordered table-striped',
        url: "/customerProductActivityRelation/selectProductDropDownSelectedListByActivityId?activityId="+ activityId,
        method: 'get',
        search: true,
        visibleSearch: true,
        customSearch: customSearch,
        pagination: true,
        pageSize: 5,
        uniqueId: 'productId',
        idField: 'productId',
        columns: [
            {field: 'productId', title: 'id', visible: false},
            {field: 'productName', title: '产品名称'},
            {field: 'productFinalPrice', title: '价格'},
            {field: 'operate', title: '操作', width: '80', align: 'right',  formatter: operateDelFormatter},
            {field: 'productCategories', title: '操作',visible: false}
        ],
        formatNoMatches:function(){
            return "暂无产品";
        },
        responseHandler: function (result) {
            if (result.code == "000000") {
                console.log(result)
                var obj = {
                    "rows": result.data
                };
            } else {
                var obj = {
                    "rows": [],
                }
            }
            return obj;
        },
        onLoadSuccess: function (data) {
            console.log(data)
        },
        onClickCell: function(field, value, row, $element) {
            if(field == 'productFinalPrice'){
                $element.attr('contenteditable', true);
                $element.blur(function() {
                    row.productFinalPrice = $element.html();
                })
            }
        }
    })
}

// 自定义删除操作
function operateDelFormatter(value, row, index) {
    var result = '<button type="button" class="btn btn-default" onclick="btnOperate(\'' + row.productId + '\', \'' + row.productName + '\', \'' + row.productCategories + '\', false)"><i class="mdi mdi-delete"></i>移除</button>';
    return result;
}

/**
 * 添加活动
 */
function editProductActivity() {
    //活动id
    var activityId = $("#activityId").val();
    //活动名称
    var productActivityName = $.trim($("#productActivityName").val());
    //起始时间
    var activityPeriodValidityStart = $("#activityPeriodValidityStart").val();
    //截止时间
    var activityPeriodValidityEnd = $("#activityPeriodValidityEnd").val();
    //起始价
    var activityPriceRangeStart = $("#activityPriceRangeStart").val();
    //截止价
    var activityPriceRangeEnd = $("#activityPriceRangeEnd").val();
    //活动价
    var activityPrice = $("#activityPrice").val();
    //兑换方式
    var exchangeMethod = $("#exchangeMethod").val();
    //产品idList
    /*var productIdList = [];
    $(".act-content").each(function(){
        $(this).find("input").each(function(){
            productIdList.push($(this).val())
        })
    })*/
    var tableDate = $('#selectedList').bootstrapTable('getData');
    var productList = [];
    var priceTotal = 0;
    for (var i = 0; i < tableDate.length; i++) {
        if(tableDate[i].productFinalPrice == ''){
            promptInfo("已选产品价格不能为空!");
            return;
        }
        priceTotal += Number(tableDate[i].productFinalPrice)
        var rowData = {
            productId: tableDate[i].productId,
            productCategories: tableDate[i].productCategories,
            productFinalPrice: tableDate[i].productFinalPrice,
        }
        productList.push(rowData);
    }

    //线索池名称为空和长度验证
    if (!productActivityName) {
        promptInfo("活动名称不能为空!");
        return;
    } else {
        if (productActivityName.length > 20) {
            promptInfo("活动名称长度不能大于20个字！");
            return;
        }
    }

    if (!activityPeriodValidityStart) {
        promptInfo("起始时间必填！");
        return;
    }

    if (!activityPeriodValidityEnd) {
        promptInfo("截止时间必填！");
        return;
    }

    if (activityPeriodValidityStart>activityPeriodValidityEnd) {
        promptInfo("起始时间必须小于截止时间！");
        return;
    }

    if (!activityPriceRangeStart) {
        promptInfo("起始价必填！");
        return;
    }

    if (!activityPriceRangeEnd) {
        promptInfo("截止价必填！");
        return;
    }

    if (parseInt(activityPriceRangeStart)>parseInt(activityPriceRangeEnd)) {
        promptInfo("起始价必须小于等于截止价！");
        return;
    }

    if (!activityPrice) {
        promptInfo("活动价必填！");
        return;
    }

    if(productList.length==0){
        promptInfo("请选择活动产品！");
        return;
    }

    if(priceTotal !== Number($('#activityPrice').val())){
        promptInfo("已选价格总和要等于活动价！");
        return;
    }
    var jsonData = {
        "productActivityId":activityId,
        "productActivityName":productActivityName,
        "activityPeriodValidityStart":activityPeriodValidityStart,
        "activityPeriodValidityEnd":activityPeriodValidityEnd,
        "activityPriceRangeStart":activityPriceRangeStart,
        "activityPriceRangeEnd":activityPriceRangeEnd,
        "activityPrice":activityPrice,
        "exchangeMethod":exchangeMethod,
        "productList":productList
    };

    console.log(productList)
    // return;
    $.ajax({
        url: '/customerProductActivity/editProductActivity',
        type: 'POST',
        dataType: "json",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify(jsonData),
        success: (function (data) {
            if(data.code == '000000'){
                $.alert({
                    title: '提示',
                    content: '修改成功！',
                    buttons: {
                        confirm: {
                            text: '确认',
                            btnClass: 'btn-primary',
                            action: function () {
                                var $thisTabs = parent.$('.mt-nav-bar .nav-tabs').find('li.active');
                                var navTab = parent.$multitabs._getNavTab($thisTabs);
                                closeTab(navTab);
                                openTab("活动列表", "/front/activityManager/productActivityForm");
                                delStorageAndRemove(navTab);
                            }
                        }
                    }
                });
            } else if(data.code == 'PA0001'){
                //活动名称重复
                $.alert(data.message);
            }else {
                $.alert("修改失败");
            }
        }),
        error: (function (res) {
            $.alert("修改失败");
        })
    })


}

function promptInfo(content) {
    $.alert({
        title: '温馨提示',
        content: content,
        buttons: {
            confirm: {
                text: '确认',
                btnClass: 'btn-primary'
            }
        }
    });
}